10801. Sum of digits

 

Given a positive integer n. Find the sum of its digits.

 

Input. The first line contains the number of test cases t (t < 100). Each of the following t lines contains a number n (1 ≤ n ≤ 1050), for which the sum of digits needs to be computed.

 

Output. Print t lines, each containing the sum of digits of the corresponding number.

 

Sample input

Sample output

3

123

43

78903

6

7

27

 

 

SOLUTION

elementary problem

 

Algorithm analysis

Since the input numbers can be very large (up to 50 digits), read them as strings. Let s be a string containing the number. For example, if s = “123”, the digit at the i-th position of the number will be s[i] – ‘0’. Sum the digits of the number at all positions.

 

Algorithm implementation

Read the number of test cases n.

 

cin >> n;

 

Process n test cases sequentially.

 

for (i = 0; i < n; i++)

{

 

Read the input number into the string s.

 

  cin >> s;

 

Compute the sum of the digits of the number in the variable sum.

 

  sum = 0;

  for (j = 0; j < s.size(); j++)

    sum = sum + s[j] - '0';

 

Print the answer.

 

  cout << sum << endl;

}

 

Python implementation

Read the number of test cases n.

 

tests = int(input())

 

Process n test cases sequentially.

 

for _ in range(tests):

 

Read the number as a string. Convert the input string into a list of digits.

 

  lst = list(map(int,input()))

 

The sum of the numbers in the list lst is equal to the sum of the digits of the current number. Print the result.

 

  print(sum(lst))